package su.msk.jet.team01.chatik.server;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.Queue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientOutputHandler extends Thread {
	private final Queue<String> messages = new LinkedList<String>();
	private final ObjectOutputStream outStream;
	private final NetworkClient client;

	private static Logger logger = LoggerFactory
			.getLogger(ClientOutputHandler.class);

	public ClientOutputHandler(final OutputStream os, final NetworkClient client)
			throws IOException {
		outStream = new ObjectOutputStream(os);
		outStream.flush();
		this.client = client;
	}

	public void close() throws IOException {
		synchronized (messages) {
			interrupt();
		}
		outStream.close();
	}

	@Override
	public void run() {
		String msg;

		try {
			synchronized (messages) {
				while (true) {
					while (messages.size() == 0) {
						try {
							messages.wait();
						} catch (InterruptedException ex) {
							// shutting down the thread
							return;
						}
					}
					msg = messages.poll();

					outStream.writeObject(msg);
					outStream.flush();
				}
			}
		} catch (IOException ex) {
			logger.warn(ex.getMessage(), ex);
		} finally {
			client.disconnect();
		}
	}

	public void sendMessage(final String msg) {
		synchronized (messages) {
			messages.add(msg);
			messages.notify();
		}
	}
}
